<script setup>
	// 图标选择组件
	import { ref, computed } from 'vue'

	const emit = defineEmits(['icoClick', 'removIco'])
	const icoSearchStr = ref('') //图标搜索框
	const layDropdownRef = ref(null) //图标弹窗ref
	const svgList = ref([])

	const svgData = import.meta.glob('@/icons/*.svg', { eager: true }) //获取icons文件夹所有svg图标的路径
	const props = defineProps({
		Icon: {
			type: String,
			default: ''
		}
	})

	const IconStr = ref(props.Icon)

	//计算SVG图标搜索列表
	const svgCompLst = computed(() => {
		if (icoSearchStr.value) {
			let searchList = svgList.value.filter(item => {
				return item.indexOf(icoSearchStr.value) != -1
			})
			return searchList
		} else {
			return svgList.value

		}
	})

	//处理路径获取对应的svg图标名称
	function getStringBetweenLastTwoPoints(str) {
		const regex = /\/([^/]+)\.svg$/;
		const match = str.match(regex);
		if (match) {
			const iconName = match[1];
			return iconName
		} else {
			return null
		}
	}
	//遍历svg文件，获取SVG文件名称集合
	for (let key in svgData) {
		let str = getStringBetweenLastTwoPoints(key)
		svgList.value.push(str)
	}

	//选择图标
	function icoClick(data) {
		IconStr.value = data
		emit('icoClick', data)
		layDropdownRef.value.hide()
	}

	//清除图标
	function removIco() {
		IconStr.value = ''
		emit('removIco')
	}
</script>

<template>
	<lay-dropdown ref="layDropdownRef" placement="bottom-start">
		<lay-input :readonly="true">
			<template #prefix>
				<svg-icon :name="IconStr || ''" class="text-xl"></svg-icon>
			</template>
			<template #suffix>
				<span class="cursor-pointer" v-if="IconStr" @click.stop="removIco">
					<lay-icon type="layui-icon-close"></lay-icon>
				</span>
			</template>
		</lay-input>
		<template #content>
			<div class="padding-sm">
				<lay-input suffix-icon="layui-icon-search" v-model="icoSearchStr"></lay-input>
			</div>
			<div class="solid-top" style="width:320px;height:300px; overflow-y: auto;">
				<lay-container fluid style="padding: 0;">
					<lay-col md="6" v-for="(item, index) in svgCompLst" :key="index" class="solid-bottom solid-right">
						<div class="cursor-pointer icon-item text-grays" @click="icoClick(item)">
							<div class="text-center padding-lg text-xl">
								<svg-icon :name="item"></svg-icon>
							</div>
						</div>
					</lay-col>
				</lay-container>
			</div>
		</template>
	</lay-dropdown>
</template>

<style scoped>

</style>